<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">

  </forms>
</template>

<script>
import {ajax} from "@/js/api_tool.js";
import {error_back, iframe} from "@/js/tool.js";
import s94Mjs from "s94-js";
import {decode_config} from "@/js/s94_tool.js";
import {S94Model} from "@/js/S94Model.js";

export default {
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;
    let model_name = this.$get('model_name', '');
    let model = S94Model.find(model_name);
    if (!model) error_back(`模型不存在：model_name=${model_name}`);

    let config_json_config = {
      ban_action: {label:'屏蔽操作',name:'ban_action',type:'text_one',tips:'屏蔽的操作名，多个逗号分隔'},
      category: {label:'分类菜单',name:'category',type:'text_one',tips:'指定作为分类菜单的父级模型名称'},
      column: {label:'列表分栏数量',name:'column',type:'text_one',config:'number',tips:'1-5'},
      mode: {label:'列表模式',name:'mode',type:'radio',config:'默认|,圆角单元格|round_row',tips:''},
    }
    let validation_json_config = {
      value: {label:'参数值',name:'value',type:'text_one_code',tips:'',inline:true},
      method: {label:'条件',name:'method',type:'select_one', config:'大于|gt,大于等于|egt,小于|lt,小于等于|elt,等于|eq,不等于|neq,包含|like,不包含|notlike',width:'100',inline:true},
      base: {label:'基准值',name:'base',type:'text_one_code',tips:'',inline:true},
      message: {label:'错误信息',name:'message',type:'text_one_code',tips:''},
      code: {label:'错误http码',name:'code',type:'text_one',config:'number',value:'403',tips:'http码约定：401未登录，402无权限，403一般验证错误，405租户过期'},
    }

    let status_config = decode_config(model.status_alias_map.status);
    let pay_status_config = decode_config(model.status_alias_map.pay_status);

    let forms_config = {
      model_name: {label:'模型',name:'model_name',type:'hidden',value:model_name},
      model: {label:'模型',name:'',type:'',value:model.label},
      type: {label:'操作类型',name:'type',type:'select_one',config:[],tips:''},
      action: {label:'操作名',name:'action',type:'text_one',tips:'格式要求：[0-9a-z_]，不可重复，不可修改'},
      label: {label:'别名',name:'label',type:'text_one',tips:''},
      // operator: {label:'操作者',name:'operator',type:'text_one',tips:'被允许的操作者，多个|分隔，anyone游客、system系统、user用户、admin管理员'},
      channel: {label:'渠道',name:'channel',type:'radio', config:{home:'用户端', admin:'管理员', system:'系统'}, tips:'操作所属渠道，'},

      tips: {label:'介绍',name:'tips',type:'text_one',tips:'备注、提示，便于识别用途'},

      need_status: {label:'状态需求',name:'need_status',type:'select_more',config:status_config,tips:'限制只能处于指定状态是，才能执行此操作。为空表示不限制'},
      need_pay_status: {label:'支付状态需求',name:'need_pay_status',type:'select_more',config:pay_status_config,tips:'限制只能处于指定支付状态是，才能执行此操作。为空表示不限制'},

      validation_json: {label:'验证规则',name:'validation_json',type:'json_param_arr',config:validation_json_config,tips:'条件判定不通过会抛出移除，提示对应的错误信息',value:'[]'},

      change_status: {label:'修改状态',name:'change_status',type:'select_one',config:status_config,tips:'执行此操作后，改变项目的状态，为空表示不改变'},
      change_pay_status: {label:'修改支付状态',name:'change_pay_status',type:'select_one',config:pay_status_config,tips:'执行此操作后，改变项目的支付状态，为空表示不改变'},

      form_param_ids: {label:'表单参数',name:'form_param_ids',type:'list_ids',config:'',tips:'操作的表单参数，如果是列表类型的操作，表示列表的列'},
      where_param_ids: {label:'筛选参数',name:'where_param_ids',type:'list_ids',config:`/model_v2_where_param/index?model_name=${model.name}`,tips:'列表操作中，筛选表单的参数'},

      base_where: {label:'检索条件',name:'base_where',type:'text_one',tips:'基础的检索条件，json字符串(支持计算code)，例如：["user_id","=","`this_user("id")`"]',value:'[]', computed:true},
      base_param: {label:'自带参数',name:'base_param',type:'text_one',tips:'自带参数，可以解决系统执行的操作需要编辑参数的需求，json字符串(支持计算code)，例如：{"user_id":`this_user("id")`}',value:'{}', computed:true},

      need_log:{label:'是否记录', name:'need_log', type:'radio_switch', config:'否|0,是|1', value:0},
      is_ban:{label:'是否禁用', name:'is_ban', type:'radio_switch', config:'禁用|1,启用|0', value:0},

      template: {label:'模板',name:'template',type:'radio',config:[],tips:''},
      page_id: {label:'页面ID',name:'page_id',type:'list_id',config:'/page/index',tips:'',value:'0'},
      init_need_param: {label:'初始化参数需求',name:'init_need_param',type:'text_one',tips:'初始化时需要的参数名，一般用于操作表单和初始化参数相关联的时候生效'},

      config_json: {label:'操作配置',name:'config_json',type:'json_param',config:config_json_config,tips:'',value:'{}'},

      execute_ids: {label:'执行操作',name:'execute_ids',type:'list_ids',config:`/execute/index?model_name=${model.name}`,tips:'操作执行时，额外的需要同时执行的系统操作'},
      sort: {label:'排序',name:'sort',type:'text_one',tips:'排序，从大到小。同时也代表着优先级',value:50},
    }
    if (id){
      forms_config.model_name.is_info = true;
      forms_config.action.is_info = true;
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }else {
      // 添加时，渠道可多选，一次添加多个操作
      forms_config.channel.type = 'checkbox';
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      btns = [];
    }
    return {
      id: id,
      btns: btns,
      config: forms_config,
      is_default: 0,
      name_has_point: false,

      model: model,
      type_map: {},
      model_map: {},
      this_model: false,
    }
  },
  methods: {
    param(data){
      data = data || {};
      data.model_name = this.model.name;
      return s94Mjs.param_encode(data);
    },
    onsubmit(formData){
      let url = this.id ? `/admin/model_v2_action/edit?id=`+this.id : '/admin/model_v2_action/add';
      ajax({url:url, method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          iframe.exe('model_v2_action/index?'+this.param(), 'getList');
          iframe.hide('model_v2_action/edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },

    change_type_after(){
      let type = this.config.type.value;
      let no_pay = !this.model.switch_pay;
      let no_param = !!~["del","restore","delete"].indexOf(type);
      let is_add = !!~["add"].indexOf(type);
      let is_list = !!~["list","group_list","export_list","recycle"].indexOf(type);
      let is_info = !!~["info","export_info"].indexOf(type);

      // 判断部分参数是否需要
      this.config.form_param_ids.remove = no_param;
      this.config.init_need_param.remove = !is_add;
      this.config.where_param_ids.remove = !is_list;
      this.config.config_json.remove = !is_list;

      this.config.need_status.remove = is_add || is_list;
      this.config.need_pay_status.remove = no_pay || is_add || is_list;

      this.config.change_status.remove = is_list;
      this.config.change_pay_status.remove = no_pay || !!is_list;

      // 判断参数类型，设定选择参数的地址
      if (!no_param){
        let param_action = 'index';
        if (is_list) param_action += '_list';
        if (is_info) param_action += '_info';
        this.config.form_param_ids.config = `/model_v2_form_param/${param_action}?model_name=${this.model.name}`;
      }

      //判定是否需要页面
      this.config.page_id.remove = !~["list","group_list",'info'].indexOf(type);

      //判定是否需要高级验证
      this.config.validation_json.remove = is_list || is_info;

      // 模板选项
      let template_config_map = {
        list: '默认|',
      }
      this.config.template.value = '';
      this.config.template.config = template_config_map[type] || '默认|';

      // 根据类型，默认操作名
      if (!this.config.action.value) this.config.action.value = type;
      if (!this.config.label.value) this.config.label.value = this.type_map[type] || '';
    },
  },
  watch: {
    'config.type.value'(v){
      this.change_type_after();
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/model_v2_action/info?id='+this.id, cache:true}, (res)=>{
        this.$refs['forms'].init(res.data);
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('model_v2_action/edit');
        }else {
          this.$router.push('index');
        }
      })
    }

    //其他初始化操作
    ajax({url:'/admin/model_v2_action/config_map',cache:true},(res)=>{
      this.type_map = res.data.type_map;
      let type_config = [
        {content:'一般操作', value:'', children:[]},
        {content:'支付相关', value:'', children:[]},
      ];
      let pay_action_list = ["pay", "cancel_pay", "pay_success", "pay_fail", "refund_apply", "refund_cancel", "refund_agree", "refund_refuse", "refund", "refund_direct", "refund_success", "refund_fail"];
      Object.keys(res.data.type_map).forEach(key=>{
        if (!~pay_action_list.indexOf(key)) {
          type_config[0]['children'].push({content:res.data.type_map[key], value:key})
        }else {
          type_config[1]['children'].push({content:res.data.type_map[key], value:key});
        }
      })
      if (!this.model.switch_pay){
        type_config = type_config[0]['children']
      }
      this.config.type.config = type_config;
      return false
    })
  }
}
</script>
